package cn.gson.financial.kernel.utils;

import cn.gson.financial.kernel.model.entity.MergeCellBean;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.MediaType;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author：ywh
 * @Date：2023/1/30 15:20
 * @Description：
 */
public class ExcelProUtil<E> {

    //注：要用此方法，实体类顺序和数量必须和表头一致
    public Workbook excelExport(List<E> list, String sheetName, String[] title, Workbook delWithWorkbook,boolean isCreateTitle) throws Exception {

        Workbook workbook;
        if (isCreateTitle){
            //创建表头
             workbook = this.createRowTitle(delWithWorkbook,title, sheetName);
        }else {
            workbook = delWithWorkbook;
        }

        if (list == null || list.size() == 0) {
            return workbook;
        }
        Field[] declaredFields = list.get(0).getClass().getDeclaredFields();

        Sheet sheet = workbook.getSheet(sheetName);
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 0; i < list.size(); i++) {
            Row row = sheet.createRow(i + 1 + lastRowNum);//i+workbook是因为此时sheet中的第一行的表头已经创建了
            for (int j = 0; j < declaredFields.length; j++) {
                String methodName = "get" + declaredFields[j].getName().substring(0, 1).toUpperCase() + declaredFields[j].getName().substring(1);
                Method method = list.get(i).getClass().getMethod(methodName, new Class[]{});
                String invoke = BaseUtil.checkValueIsNull((String) method.invoke(list.get(i), new Object[]{}));
                Cell cell = row.createCell(j);
                cell.setCellType(CellType.STRING);
                if (invoke == null || invoke.contains("null")){
                    cell.setCellValue("");
                }else {
                    cell.setCellValue(invoke);
                }
            }
        }
        return workbook;
    }

    //判断文件是否存在，如果不存在，就创建个XSSFWorkbook，如果存在，就读取该文件生成XSSFWorkbook
    public Workbook getWorkBook(String filePath) throws IOException {
        File file = new File(filePath);
        if (file.exists()){
            FileInputStream fileInputStream = new FileInputStream(filePath);
            Workbook workbook = new XSSFWorkbook(fileInputStream);
            return workbook;
        }
        return new XSSFWorkbook();
    }

    public Workbook createRowTitle(Workbook workbook, String[] title, String sheetName) {
        Sheet sheet = workbook.getSheet(sheetName);
        if (sheet == null){
            sheet = workbook.createSheet(sheetName);
        }
        int lastRowNum = sheet.getLastRowNum();
        Row rowTitle = sheet.createRow((lastRowNum==0)?lastRowNum:lastRowNum+1);
        for (int i = 0; i < title.length; i++) {
            Cell cell = rowTitle.createCell(i);
//            cell.setCellType(Cell.CELL_TYPE_STRING);//3.8版本用的
            cell.setCellType(CellType.STRING);//4.1版本
            cell.setCellValue(title[i]);
        }
        return workbook;
    }

    public void excelResponse(Workbook workbook,String fileName,HttpServletResponse response) throws IOException {

        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" +  java.net.URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/octet-stream");
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
